import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

export const asyncTodos = createAsyncThunk('yyy', (id) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(id)
    }, 2000)
  })
})

export default createSlice({
  name: 'todos',
  initialState: {
    todos: JSON.parse(localStorage.getItem('todos')) || [],
    editId: undefined,
    loading: false, // 用来控制是否展示`正在删除....`.false就是不展示.true就是展示
  },
  // 同步的
  reducers: {
    addTodo(state, action) {
      // 根据任务名创建任务对象
      const obj = {
        id: Date.now(),
        todoName: action.payload,
        isDone: false,
      }

      state.todos.push(obj)

      // state.todos = state.todos
    },

    updateTodo(state, action) {
      state.todos.forEach((item) => {
        if (item.id === action.payload) {
          item.isDone = !item.isDone
        }
      })
      // state.todos = state.todos
    },

    delTodo(state, action) {
      state.todos = state.todos.filter((item) => {
        return item.id !== action.payload
      })
    },

    allCheck(state, action) {
      state.todos.forEach((item) => {
        item.isDone = action.payload
      })
      // state.todos = state.todos
    },

    clearAllDone(state, action) {
      state.todos = state.todos.filter((item) => !item.isDone)
    },
    setEditId(state, action) {
      state.editId = action.payload
    },
    setTodoName(state, action) {
      const { id, todoName } = action.payload

      state.todos.forEach((item) => {
        if (item.id === id) {
          item.todoName = todoName
        }
      })
      state.editId = undefined
    },
  },

  // 异步的
  extraReducers(builder) {
    // 监听异步正在执行的回调
    builder.addCase(asyncTodos.pending, (state, action) => {
      // 异步执行的时候展示一个正在删除的效果
      state.loading = true
    })
    // 监听异步失败执行的回调
    builder.addCase(asyncTodos.rejected, (state, action) => {
      state.loading = false
    })

    // 监听了异步成功的回调
    builder.addCase(asyncTodos.fulfilled, (state, action) => {
      // 异步成功的时候,隐藏这个正在删除的效果
      state.loading = false
      state.todos = state.todos.filter((item) => {
        return item.id !== action.payload
      })
    })
  },
})
